package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.dao.AgentInfoMapper;
import cc.rengu.igas.bomp.common.dao.OrgInfoMapper;
import cc.rengu.igas.bomp.common.dao.OrganizationMapper;
import cc.rengu.igas.bomp.common.dao.impl.AgentInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.OrgInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.OrganizationMapperImpl;
import cc.rengu.igas.bomp.common.entity.AgentInfo;
import cc.rengu.igas.bomp.common.entity.ManagerInfo;
import cc.rengu.igas.bomp.common.entity.OrgInfo;
import cc.rengu.igas.bomp.common.entity.Organization;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.OrgInfoBean;
import cc.rengu.igas.bomp.facade.request.OrgInfoListQueryRequest;
import cc.rengu.igas.bomp.facade.response.OrgInfoListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 机构列表查询服务
 * Edit by 赵奎伍
 * <p/>
 * 根据userId获取扩展经理信息,然后根据拓展经理签约机构,结合查询条件,查询该机构及该机构下符合的机构列表信息.
 */
public class OrgInfoListQueryService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        OrgInfoListQueryRequest orgInfoListQueryRequest = new OrgInfoListQueryRequest();
        ConvertUtil.convertOutput(orgInfoListQueryRequest);
        return orgInfoListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        OrgInfoListQueryRequest requestParams = (OrgInfoListQueryRequest) request;
        OrgInfoListQueryResponse responseParams = new OrgInfoListQueryResponse();
        BeanUtil.beanCopy(requestParams, responseParams);
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setResult(responseParams);
        String instId = requestParams.getHeader().getInstId();

        String orgCode = requestParams.getOrgCode();//机构标志
        String orgName = requestParams.getOrgName();//机构名称
        String orgType = requestParams.getOrgType();//机构类型
        orgType = StringUtil.isEmptyOrNull(orgType) ? "00" : orgType;
        int pageIndex = requestParams.getPageIndex();
        int pageSize = requestParams.getPageSize();
        rglog.debug("查询字段:orgCode<{}>,orgName<{}>,pageIndex<{}>,pageSize<{}>", orgCode, orgName, pageIndex, pageSize);

        if (!ChannelEnum.UPMP.getChannelType().equals(requestParams.getHeader().getSrcSysId())) {
            OrganizationMapper organizationMapper = new OrganizationMapperImpl();
            /**签约机构号*/
            String superOrgCode = null;
            //拓展经理信息已在【ManageService】中获取,签约机构及其下属机构,然后根据机构列表查询
            ManagerInfo managerInfo = (ManagerInfo) xmlTreeUtil.getXmlTreeObjectValue("managerInfo", ManagerInfo.class);
            if ("AGENT".equals(managerInfo.getSignInstType())) {
                //拓展经理签约机构为【代理商】,查询代理商的管理机构作为上级机构查询
                AgentInfoMapper agentInfoMapper = new AgentInfoMapperImpl();
                AgentInfo agentInfo = agentInfoMapper.selectAgentInfoByPrimaryKey(instId, managerInfo.getSignInstId());
                if (null == agentInfo || !"01".equals(agentInfo.getAgentStatus())) {
                    rglog.error("代理商不存在或代理商状态非正式<{}>", JSONObject.toJSONString(agentInfo));
                    throw new BizException(RespCodeEnum.AGENT_ERROR.getRespCode(), RespCodeEnum.AGENT_ERROR.getRespDesc());
                }
                superOrgCode = agentInfo.getManageInstId();
            } else {
                superOrgCode = managerInfo.getSignInstId();
            }


            List<Organization> organizationList = new ArrayList<>();
            if (-1 == pageIndex || -1 == pageSize) {
                //不分页
                organizationList = organizationMapper.selectOrgInfoByInstCodeAndInstName(instId, superOrgCode, orgCode, orgName);
                if (organizationList == null || organizationList.size() == 0) {
                    rglog.info("根据查询条件查询到0条机构列表信息.");
                    responseParams.setTotalPage(BompAppParamConstant.INT_ZERO);
                    responseParams.setTotalRows(BompAppParamConstant.INT_ZERO);
                    responseParams.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    responseParams.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    bizResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    bizResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }
            } else {
                PageInfo pageInfo = new PageInfo();
                pageInfo.setPageIndex(pageIndex);
                pageInfo.setPageSize(pageSize);
                PageResult pageResult = organizationMapper.selectOrgInfoByPageAndInstCodeAndInstName(instId, superOrgCode, orgCode, orgName, pageInfo);
                if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult() || pageResult.getResult().isEmpty()) {
                    rglog.info("根据查询条件查询到0条机构列表信息.");
                    responseParams.setTotalPage(BompAppParamConstant.INT_ZERO);
                    responseParams.setTotalRows(BompAppParamConstant.INT_ZERO);
                    responseParams.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    responseParams.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    bizResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    bizResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }

                for (Object object : pageResult.getResult()) {
                    organizationList.add((Organization) object);
                }
                responseParams.setTotalPage(pageResult.getPageInfo().getTotalPage());
                responseParams.setTotalRows(pageResult.getPageInfo().getTotalRows());
            }
            rglog.info("SIZE=<{}>", organizationList.size());
            if (!organizationList.isEmpty()) {
                /** 按照创建时间降序排序 */
                List<OrgInfoBean> orgInfoBeanList = new ArrayList<>();
                organizationList.forEach(item -> convIndustryInfo(item, orgInfoBeanList));
                responseParams.setOrgInfoList(orgInfoBeanList);
            }
        } else {
            List<OrgInfo> orgInfoList;
            OrgInfoMapper orgInfoMapper = new OrgInfoMapperImpl();
            /* 根据机构号及机构名称先查询出所有匹配的机构信息 */
            ManagerInfo managerInfo = (ManagerInfo) xmlTreeUtil.getXmlTreeObjectValue("managerInfo", ManagerInfo.class);
            if ("AGENT".equals(managerInfo.getSignInstType())) {
                //拓展经理签约机构为【代理商】,查询代理商的管理机构作为上级机构查询
                AgentInfoMapper agentInfoMapper = new AgentInfoMapperImpl();
                AgentInfo agentInfo = agentInfoMapper.selectAgentInfoByPrimaryKey(instId, managerInfo.getSignInstId());
                if (null == agentInfo || !"01".equals(agentInfo.getAgentStatus())) {
                    rglog.error("代理商不存在或代理商状态非正式<{}>", JSONObject.toJSONString(agentInfo));
                    throw new BizException(RespCodeEnum.AGENT_ERROR.getRespCode(), RespCodeEnum.AGENT_ERROR.getRespDesc());
                }
                orgType = "01";
                orgCode = managerInfo.getSignInstId();
            } else {
                orgCode = managerInfo.getSignInstId();
            }
            /* 根据查询到的机构信息，查询其下属机构 */
            List<OrgInfoBean> orgInfoBeanList = new ArrayList<>();
            if (-1 == pageIndex || -1 == pageSize) {
                orgInfoList = orgInfoMapper.selectOrgInfoByOrgCodeOrOrgName(instId, orgType, orgCode, orgName);
                if (orgInfoList == null || orgInfoList.size() == 0) {
                    rglog.info("根据查询条件查询到0条机构列表信息.");
                    responseParams.setTotalPage(BompAppParamConstant.INT_ZERO);
                    responseParams.setTotalRows(BompAppParamConstant.INT_ZERO);
                    responseParams.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    responseParams.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    bizResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    bizResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }
                orgInfoList.forEach(item -> convOrgInfo(item, orgInfoBeanList));
            } else {
                PageInfo pageInfo = new PageInfo();
                pageInfo.setPageIndex(pageIndex);
                pageInfo.setPageSize(pageSize);
                PageResult pageResult = orgInfoMapper.selectOrgInfoByOrgCodeOrOrgName(instId, orgType, orgCode, orgName, pageInfo);
                if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult() || pageResult.getResult().isEmpty()) {
                    rglog.info("根据查询条件查询到0条机构列表信息.");
                    responseParams.setTotalPage(BompAppParamConstant.INT_ZERO);
                    responseParams.setTotalRows(BompAppParamConstant.INT_ZERO);
                    responseParams.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    responseParams.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    bizResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    bizResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }
                for (Object object : pageResult.getResult()) {
                    convOrgInfo((OrgInfo) object, orgInfoBeanList);
                }
                responseParams.setTotalPage(pageResult.getPageInfo().getTotalPage());
                responseParams.setTotalRows(pageResult.getPageInfo().getTotalRows());
            }
            rglog.info("SIZE=<{}>", orgInfoBeanList.size());
            responseParams.setOrgInfoList(orgInfoBeanList);
        }
        /* 按照接口转换基础产品信息并响应给请求方 */
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        OrgInfoListQueryResponse instInfoQueryResponse = (OrgInfoListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(instInfoQueryResponse);
    }

    /**
     * 将数据库表结构对象转换成接口对象
     *
     * @param orgInfo         数据库表结构对象
     * @param orgInfoBeanList 接口对象
     */
    private void convOrgInfo(OrgInfo orgInfo, List<OrgInfoBean> orgInfoBeanList) {
        OrgInfoBean orgInfoBean = new OrgInfoBean();
        BeanUtil.beanCopy(orgInfo, orgInfoBean);
        try {
            OrgInfoMapper orgInfoMapper = new OrgInfoMapperImpl();
            OrgInfo superOrgInfo = orgInfoMapper.selectOrgInfoByPrimaryKey(orgInfo.getInstId(), orgInfo.getOrgType(), orgInfo.getSuperOrgCode());
            if (null != superOrgInfo) {
                orgInfoBean.setSuperOrgName(superOrgInfo.getOrgName());
            }
        } catch (Exception e) {
            rglog.warn("获取该机构的上级机构信息失败,该机构代码:<{}>,上级机构代码:<{}>", orgInfo.getOrgCode(), orgInfo.getSuperOrgCode());
        }
        orgInfoBeanList.add(orgInfoBean);
    }

    /**
     * 将数据库表结构对象转换成接口对象
     *
     * @param organization    数据库表结构对象
     * @param orgInfoBeanList 接口对象
     */
    private void convIndustryInfo(Organization organization, List<OrgInfoBean> orgInfoBeanList) {
        OrgInfoBean orgInfoBean = new OrgInfoBean();
        // BeanUtil.beanCopy(organization, instInfo);
        if (organization != null) {
            orgInfoBean.setOrgCode(organization.getOrgCode());
            orgInfoBean.setOrgName(organization.getOrgName());
            orgInfoBean.setSuperOrgCode(organization.getSuperOrgCode());
            orgInfoBean.setSuperOrgName("");
            OrganizationMapper organizationMapper = new OrganizationMapperImpl();
            Organization superOrganization = null;
            try {
                superOrganization = organizationMapper.selectOrganizationByPrimaryKey(organization.getInstId(), organization.getSuperOrgCode());
                if (null != superOrganization) {
                    orgInfoBean.setSuperOrgName(superOrganization.getOrgName());
                }
            } catch (Exception e) {
                rglog.error("获取该机构的上级机构信息失败,该机构代码:<{}>,上级机构代码:<{}>", organization.getOrgCode(), organization.getSuperOrgCode());
            }
        }
        orgInfoBeanList.add(orgInfoBean);
    }
}
